/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.querydsl;

import java.util.ArrayList;
import java.util.List;

import com.querydsl.core.types.Path;
import com.querydsl.sql.RelationalPath;
import net.apexes.commons.lang.Checks;

/**
 * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
 */
public class IncludeColumns {

    public static IncludeColumns of(RelationalPath<?> path) {
        return new IncludeColumns(path);
    }

    public static IncludeColumns of(Path<?>... includeColumns) {
        return new IncludeColumns(includeColumns);
    }

    private Path<?>[] includeColumns;

    public IncludeColumns(RelationalPath<?> path) {
        this.includeColumns = path.getColumns().toArray(new Path<?>[0]);
    }

    public IncludeColumns(Path<?>... includeColumns) {
        this.includeColumns = includeColumns;
    }

    public IncludeColumns add(IncludeColumns include) {
        Checks.verifyNotNull(include, "include");
        if (include.includeColumns != null) {
            return add(include.includeColumns);
        } else {
            return this;
        }
    }

    public IncludeColumns add(Path<?>... includeColumns) {
        Checks.verifyNotEmpty(includeColumns, "includeColumns");
        List<Path<?>> list = new ArrayList<Path<?>>(this.includeColumns.length + includeColumns.length);
        for (Path<?> column : this.includeColumns) {
            list.add(column);
        }
        for (Path<?> column : includeColumns) {
            if (!list.contains(column)) {
                list.add(column);
            }
        }
        this.includeColumns = list.toArray(new Path<?>[list.size()]);
        return this;
    }

    public Path<?>[] getIncludeColumns() {
        if (includeColumns == null) {
            List<Path<?>> list = new ArrayList<>(0);
            includeColumns = list.toArray(new Path<?>[0]);
        }
        return includeColumns;
    }

    public boolean hasColumns() {
        return (includeColumns == null || includeColumns.length == 0) ? false : true;
    }

}
